// RequestJs.js
// JireClient.js
// jQuery.js
// RequestJs.js
// JiraClient.js
class JiraActions
{
    constructor(options)
    {
        if (Object.keys(options.source).length &&
            Object.keys(options.target).length
        ) {
            if (options.source.url && !options.source.host) {
                options.source.host = options.source.url;
            }
            if (options.target.url && !options.target.host) {
                options.target.host = options.target.url;
            }
            this.sourceJira = new JiraClient(options.source);
            this.targetJira = new JiraClient(options.target);
        }
    }

    async updateIssues(issueKeyOrIds, field, value)
    {
        let self = this;
        issueKeyOrIds.forEach(issueKeyOrId => {
            let updateData = {"fields":{}};
            updateData.fields[field] = value;

            console.log('##updateData', updateData);
            // update issue
            self.sourceJira.updateIssue(issueKeyOrId, updateData).then(resp => {
                console.log('##Update result', resp.status)
                if (resp.status==204) {
                    jQuery('#' + issueKeyOrId).after('<span class="update-status-res" style="color:green">Updated</span>').prop("checked", false);
                }
            });
            updateData = {fields:{}};
            console.log('##update source issue', issueKeyOrId);
        });

        issueKeyOrIds.forEach(ticketId => {
            self.getRelatedIssues(ticketId)
                .then(resp => resp.json())
                .then(result => {
                if (result.total) {
                    result.issues.forEach(issue => {
                        let updateData = {};
                        if (field=='fixVersions') {
                            value.forEach(item => {
                                //updateData.fields[field] = value;
                                updateData.update = {
                                    "fixVersions": [
                                        {"add": {"name": item.name}}
                                    ]
                                };
                                self.targetJira.updateIssue(issue.key, updateData);
                            });
                        } else {
                            updateData.fields[field] = value;
                            self.targetJira.updateIssue(issue.key, updateData);
                        }

                        console.log('##update target issue', issue.key);
                    });
                }
            });
        });
    }

    async getRelatedIssues(issueKeyOrId)
    {
        let self = this;
        let jql = 'project = HSI AND type in(Bug, Task) AND ("Ticket ID" ~ ' + issueKeyOrId + ' OR summary ~  ' + issueKeyOrId + ')';
        return await self.targetJira.search(jql, {size:200});
    }

    async updateFields()
    {
        let self = this;
        let list = [];
        jQuery('.update-keys:checked').each(function(idx, item) {
            list.push(jQuery(item).val());
        });

        let field = jQuery('#jira-actions .field').val();
        let value = jQuery('#jira-actions .value').val();
        if (value.length && list) {
        // {
        //     "fields":{
        //         "fixVersions":[
        //             {"name":"v1.22.1108"}
        //         ]
        //     }
        // }

            let _value = '';
            if (field==='fixVersions') {
                _value = [{name: value}];
            } else {
                _value = {name: value};
            }

            await self.updateIssues(list, field, _value).then(resp => {
                jQuery('#jira-actions-render').trigger('click');
            });
        }

        console.log('##updateFields', list);
    }

    async collectResourceData()
    {
        let fixVersion = '';
            fixVersion = jQuery('#issuetable tbody tr:eq(0) .fixVersions a').text();

        if (fixVersion=='') {
            alert('Search can not get fixVersion!');
            throw new Exception('##Can not get fixVersion!');
        }

        let self = this;
        let issues = await self.getCurrentData(fixVersion);
        let data = {};
        let regex = /^HPST-\d+/;
        if (issues.length) {
            issues.forEach((issue, idx) => {
                // name or displayName
              	//let key = issue.fields.customfield_10700;
                var tmp = issue.fields.summary.match(regex);
                let key = (tmp==null) ? '' : tmp[0];
                let uname = 'none';

                if (tmp==null) {
                    console.log('##issue null:', issue);
                } else {
                    console.log('##issue', issue);
                }

                if (Object.prototype.toString.call(issue.fields.assignee) != '[object Null]') {
                    uname = issue.fields.assignee?.displayName;
                }
                if (!data[key]) {
                    data[key] = {
                        key: issue.key,
                        ticket: key,//issue.fields.customfield_10700,
                        assignee: uname,
                        type: issue.fields.issuetype.name,
                        summary: issue.fields.summary,
                        status: issue.fields.status.name
                    }

                    // if is WOC
                    if (data[key].status.toLocaleUpperCase()=='IN PROGRESS') {
                        issue.fields.labels.forEach(label => {
                            if (label.toLocaleUpperCase() == 'WOC') {
                                data[key].status = 'WOC';
                            }
                        });
                    }
                }
            });
        }
      	console.log('##resources list', data);
        return data;
    }

    /**
     *
     * @param string fixVersion
     * @returns array
     */
    async getCurrentData(fixVersion)
    {
        let jql = 'project = HSI AND type in (Bug, Task) AND fixVersion = ' + fixVersion + ' ORDER BY assignee ASC, status DESC';
        let issues = [];
        let respPromise = await this.targetJira.search(jql, {size: 200})
                .then(resp => resp.json())
                .then(resp => {
                    if (resp.total) {
                        issues = resp.issues;
                    }
                });
        return issues;
    }

    async getAssignAndTargetTicketInfo()
    {
        let self = this;
        let rows = await self.collectResourceData();
        // let rows = {
        //     'HPST-45117':{
        //         key: 'key',
        //         ticket: 'HPST-45117',
        //         assignee: 'Luo',
        //         summary: 'summary',
        //         status: 'Done'
        //     }
        // };

        let options = {
            'reset': "Reset"
        };
        jQuery('.issuerow').each(function(idx, row) {
            let issueKey = jQuery(row).data('issuekey');
            let taskInfo = '';
            if (rows[issueKey]) {
                taskInfo += '<ul><li style="color:blue;">' + rows[issueKey].assignee + '</li>';
                taskInfo += '<li style="color:red;">' + rows[issueKey].status + '</li>';
                taskInfo += '<li>' + rows[issueKey].type + '</li>';
                taskInfo += '<li><a href="' + self.targetJira.host+ '/browse/' + rows[issueKey].key + '" " target="new">' + rows[issueKey].key + '</a></li>';
                taskInfo += '</ul>'
                // add class to each row
                jQuery(row).addClass(rows[issueKey].assignee?.toLowerCase()?.replace(' ', '-'));
                options[rows[issueKey].assignee?.toLowerCase()?.replace(' ', '-')] = rows[issueKey].assignee;

                jQuery('.customfield_13700', jQuery(row))
                    .html('')
                    .html(taskInfo);
            }
        });

        // render filer
        Object.entries(options).forEach(([key, value]) => {
            let option = document.createElement('option');
            option.value = key;
            option.text = value;
            document.getElementById('resource-filter').add(option);
        });

        jQuery('#resource-filter').show().on('change', function() {
            let filter = jQuery(this).val();
            jQuery('.issuerow').removeClass('hidden');
            if (filter!='reset') {
                jQuery('.issuerow').not('.' + filter).addClass('hidden');
            }
        });
    }

    addCheckBox()
    {
        let self = this;
        jQuery('.issuekey').each(function(idx, item) {
            // get key
            let key = jQuery('.issue-link', item).data('issue-key');
            // add checkbox
            jQuery(item).append('<input id="' + key + '" class="update-keys" type="checkbox" name="kyes[]" value="' + key + '"/>');
        });
    }

    selectedAll()
    {
        jQuery('.update-keys').each(function(idx, item) {
            if (jQuery(item).prop('checked')) {
                jQuery(item).prop('checked', false);
            } else {
                jQuery(item).prop('checked', true);
            }
        });
    }

    renderFixVersionForm()
    {
        let self = this;
        let html = '';
            html += `
            <div id="jira-actions" style="margin: 5px;">
            <ul style="list-style: none;display: flex;justify-content: start;align-items: start;">
                <li>
                    <select class="field">
                        <option value="fixVersions">fixVersions</option>
                        <option value="priority">priority</option>
                        <option value="assignee">assignee</option>
                    </select>
                </li>
                <li><input class="value" name="fixVersion"></li>
                <li>&nbsp;</li>
                <li><button id="jira-actions-update" type="button">Update</button></li>
                <li><button id="jira-actions-render" type="button">Render</button></li>
                <li><button id="jira-actions-select-all" type="button">Selected All</button></li>
                <li><select id="resource-filter" style="display:none;"></select></li>
            </ul>
            </div>
            `;

        jQuery('#jira-actions').remove();
        jQuery('.issue-search-header').append(html);
        jQuery('#jira-actions-select-all').on('click', function(){
            self.selectedAll();
        });
        jQuery('#jira-actions-update').on('click', function(){
            self.updateFields();
        });
        jQuery('#jira-actions-render').on('click', function(){
            jQuery('.update-keys').remove();
            jQuery('.update-status-res').remove();
            self.addCheckBox();
            // render developer
            self.getAssignAndTargetTicketInfo();
        });
        self.addCheckBox();
    }

    isset(value)
    {
        return '[object Undefined]' != Object.prototype.toString.call(value);
    }
}
var jiraAction = new JiraActions(JSON.parse(localStorage.getItem('config')));
jiraAction.renderFixVersionForm();